package com.gaojinqi.base.core.jpa.util;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 注解查询 - 分组帮助类
 *
 * @author gaojinqi
 * @version 1.0
 * @since 2020年06月24日
 */
public class QueryGroupHelper {

    private static InheritableThreadLocal<Map<Object, Set<Class<?>>>> GROUP_THREAD_LOCAL = new InheritableThreadLocal<>();

    static {
        Map<Object, Set<Class<?>>> groupMap = GROUP_THREAD_LOCAL.get();
        if (groupMap == null) {
            GROUP_THREAD_LOCAL.set(new ConcurrentHashMap<>());
        }
    }

    /**
     * 对某个对象设置分组
     */
    public static boolean hasBean(Object bean) {
       return getGroupMap().containsKey(bean);
    }

    /**
     * 对某个对象设置分组
     */
    public static void setGroups(Object bean, Class<?>... groups) {
        Map<Object, Set<Class<?>>> groupMap = getGroupMap();
        Set<Class<?>> groupSet = new LinkedHashSet<>();
        if (groups != null) {
            Collections.addAll(groupSet, groups);
        }
        groupMap.put(bean, groupSet);
    }

    /**
     * 返回某个对象设置分组
     */
    public static Set<Class<?>> getGroups(Object bean) {
        return getGroupMap().get(bean);
    }

    /**
     * 清空某个对象设置分组
     */
    public static void clearGroups(Object bean) {
        getGroupMap().remove(bean);
    }


    private static Map<Object, Set<Class<?>>> getGroupMap() {
        Map<Object, Set<Class<?>>> groupMap = GROUP_THREAD_LOCAL.get();
        if (null == groupMap) {
            synchronized (QueryGroupHelper.class) {
                if (null == groupMap) {
                    groupMap = new ConcurrentHashMap<>();
                    GROUP_THREAD_LOCAL.set(groupMap);
                }
            }
        }
        return groupMap;
    }
}


